<template>
    <div class="app-container">

        <el-form
            class="searchForm"
            :inline="true"
            size="mini"
            ref="searchForm"
            :model="searchForm"
        >
            <el-form-item label="名称">
                <el-input
                    clearable
                    v-model="searchForm.name"
                    placeholder="请输入名称"
                />
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-search"
                    @click="doSearch"
                >搜索
                </el-button
                >
                <el-button
                    type="default"
                    size="mini"
                    icon="el-icon-refresh"
                    @click="resetSearch"
                >重置
                </el-button
                >
            </el-form-item>
        </el-form>
        <div class="searchs-content">
            <el-button
                v-permission="['om:product:add']"
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="addDialog"
            >新增
            </el-button
            >
        </div>

        <Table
            :tableHeader="tableHeader"
            :tableData="tableData"
            :tableLoading="listLoading"
        >

            <template slot="action" slot-scope="scope">
                <el-button
                    type="primary"
                    size="mini"
                    @click="handleGenerate(scope.row)"
                >生成二维码</el-button>
                <el-button
                    v-permission="['om:product:update']"
                    type="primary"
                    size="mini"
                    @click="handleUpdate(scope.row)"
                >编辑</el-button>
                <el-button
                    v-permission="['om:product:delete']"
                    type="danger"
                    size="mini"
                    @click="handleDelete(scope.row)"
                >删除 </el-button>
            </template>
        </Table>
        <pagination
            v-if="total > 0"
            :total="total"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="fetchData"
        />

        <!--    新增    -->
        <el-dialog title="新增" :visible.sync="insertVisible" top="20vh" width="60%" :top="'5%'"
                   class="home-confirm-dialog" v-if="insertVisible">

            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" size="small">

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="ruleForm.name" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="版本类型" prop="type">
                            <el-input v-model="ruleForm.type" placeholder="请输入"></el-input>
<!--                            <el-select v-model="ruleForm.type" clearable placeholder="请选择">-->
<!--                                <el-option v-for="item in enumsJson.PRODUCT_TYPE" :key="item.code" :label="item.label"-->
<!--                                           :value="item.code"></el-option>-->
<!--                            </el-select>-->
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col>
                        <el-form-item label="图片" prop="pictures">


                            <el-upload ref="productPictures" action="#" list-type="picture-card" :http-request="uploadRequest" accept=".jpg,.jpeg,.png"
                                       :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="ruleForm.pictures">
                                <div v-if="ruleForm.pictures.length > 0" slot="file" slot-scope="{file}">
                                    <img class="el-upload-list__item-thumbnail" :src="file.path + file.name"  alt="" >
                                    <span class="el-upload-list__item-actions">
                                        <span><i class="el-icon-zoom-in" @click="zoomInFile(file)"></i></span>
                                       <span><i class="el-icon-delete-solid" @click="deletePicture(file)"></i></span>
                                     </span>
                                </div>
                                <i class="el-icon-plus"></i>
                            </el-upload>

                            <el-dialog width="35%" :visible.sync="dialogVisible" append-to-body>
                                <img width="100%" height="50%" :src="dialogImageUrl" alt="">
                            </el-dialog>

                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col>
                        <el-form-item label="产品规格" prop="specifications">

                            <el-row >
                                <el-col :span="2">
                                    <el-button @click="addDomain">新增规格</el-button>
                                </el-col>

                                <el-col>
                                    <span style="color: red">示例： 规格名称：尺寸（高×宽×深） &nbsp;&nbsp;&nbsp; 规格值：1800mm*1000mm*500mm（含底座）</span>
                                </el-col>

                                <el-col>

                                    <div v-for="(domain, index) in ruleForm.specifications">

                                        <el-row :gutter="20">
                                            <el-col :span="10">
                                                <el-form-item label="规格名称" :prop="'specifications.' + index + '.nameKey'" :rules="{ required: true, message: '规格名称不能为空', trigger: 'blur'}">
                                                    <el-input v-model="domain.nameKey"></el-input>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="10">
                                                <el-form-item label="规格值" :prop="'specifications.' + index + '.nameValue'" :rules="{ required: true, message: '规格值不能为空', trigger: 'blur'}">
                                                    <el-input v-model="domain.nameValue"></el-input>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="4">
                                                <el-button @click.prevent="removeDomain(domain)">删除</el-button>
                                            </el-col>
                                        </el-row>

                                    </div>
                                </el-col>
                            </el-row>

                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col>
                        <el-form-item label="产品文件" prop="files">

                            <el-row :gutter="20">
                                <el-col :span="3">
                                    <el-button @click="addFiles">新增产品文件</el-button>
                                </el-col>
                                <el-col>
                                    <div v-for="(afile, index) in ruleForm.files" style="margin-top: 10px;">

                                        <el-row :gutter="20">
                                            <el-col :span="1"><div class="grid-content bg-purple"></div>
                                            </el-col>
                                            <el-col :span="8">
                                                <el-form-item label="文件类型" :prop="'files.' + index + '.type'" :rules="{required: true, message: '请选择', trigger: 'change'}">
                                                    <el-autocomplete v-model="afile.type" :fetch-suggestions="querySearchAsync" placeholder="请输入" style="width: 25vh" @select="handleSelect"></el-autocomplete>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="6">
                                                <el-form-item label="文件" :prop="'files.' + index + '.fileList'" :rules="{type: 'array', required: true, message: '请上传文件', trigger: 'change'}">

                                                    <el-upload class="avatar-uploader" action="#" accept=".pdf, .doc, .docx,.jpg,.jpeg,.png"
                                                               :http-request="(params) => uploadFilesRequest(params, index)" :file-list="afile.fileList" :on-success="handleAvatarSuccess"
                                                               v-loading.fullscreen.lock="uploading" element-loading-text="拼命上传中"
                                                               element-loading-spinner="el-icon-loading" element-loading-background="rgba(0,0,0,0.1)">

                                                        <el-button size="small" type="primary">点击上传</el-button>
                                                    </el-upload>

                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="3">
                                                <el-button @click.prevent="removeFiles(afile)">删除</el-button>
                                            </el-col>
                                        </el-row>

                                    </div>
                                </el-col>
                            </el-row>

                        </el-form-item>
                    </el-col>
                </el-row>


                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                    <el-button v-if="ruleForm.id == null" @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
            </el-form>

        </el-dialog>

    </div>
</template>

<script>
import {product} from "@/api/manage";
import {removeNullUndefined} from "@/utils";
import Pagination from "@/components/Pagination";
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";
import {handleConfirm} from "@/utils/messageBox";

export default {
    components: {Pagination, Table, Dialog},
    data() {
        return {
            tableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                {
                    label: "产品名称",
                    prop: "name",
                },
                {
                    label: "类型",
                    prop: "type",
                },
                {
                    label: "创建人",
                    prop: "createBy",
                },
                {
                    label: "创建时间",
                    prop: "createTime",
                },
                {slot: "action", label: "操作", width: "250"},
            ],
            tableData: [],
            listLoading: true,
            total: 0,
            searchForm: {
                pageNum: 1,
                pageSize: 15,
                name: "",
            },

            enumsJson: {}, //枚举

            dialogImageUrl: '',
            images: [],
            dialogVisible: false,
            insertVisible: false,
            ruleForm: {
                id: '',
                name: '',
                type: '',
                pictures: [],
                specifications: [
                    {nameKey: '', nameValue: ''}
                    ],
                files: [
                    {type: '', fileList: []}
                    ],
            },
            rules: {
                name: [
                    {required: true, message: '请输入名称', trigger: 'blur'}
                ],
                type: [
                    {required: true, message: '请输入', trigger: 'blur'}
                ],
                pictures: [
                    {type: 'array', required: true, message: '请至少上传一个图片', trigger: 'change'}
                ],
                specifications: [
                    {type: 'array', required: true, message: '请至少上传一个图片', trigger: 'change'}
                ],
                files: [
                    {type: 'array', required: true, message: '请至少上传一个类型文件', trigger: 'change'}
                ],
            },

            fileTypeOption: [],
            timeout:  null,

            //文件列表
            uploading: false,

            IMGLink: this.IMGLink,
            isMax: true,
        }
    },
    async created() {
        this.enumsJson = await this.$store.dispatch("enums/generateEnumMap");
        this.fetchData();
    },
    methods: {
        fetchData(val) {
            this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
            this.listLoading = true;
            this.tableData = [];
            this.total = 0;
            product("/list", "get", {...removeNullUndefined(this.searchForm)})
                .then((res) => {
                    this.tableData = res.data;
                    this.total = +res.total;

                    this.searchForm.pageNum = +res.pageNum;
                })
                .finally(() => {
                    this.listLoading = false;
                });
        },

        resetSearch() {
            this.searchForm = {
                pageNum: this.searchForm.pageNum,
                pageSize: this.searchForm.pageSize,
                name: "",
            };
        },
        doSearch() {
            this.searchForm.pageNum = 1;
            this.fetchData();
        },
        //编辑：
        handleUpdate(row){
            this.insertVisible = true;
            console.log(row)

            let specifications = row.specificationsList.map(item => {
                return {
                    nameKey: item.nameKey,
                    nameValue: item.nameValue
                }
            })

            let files = row.files.map(item => {
                return {
                    type: item.type,
                    fileList: [{name: item.fileName, url: item.filePath}]
                }
            })

            let pic = row.pictures.split(",").map(item => {
                return {
                    path: this.IMGLink,
                    name: item,
                    url: item,
                };
            })

            // this.images = pic;

            this.ruleForm = {
                id: row.id,
                name: row.name,
                type: row.type,
                pictures: pic,
                specifications: specifications,
                files: files
            }

            console.log("编辑按钮")
            console.log(this.ruleForm)
        },

        // 新增
        addDialog(row) {
            this.insertVisible = true;
            this.images = []
            this.dialogImageUrl = ''

            this.ruleForm = {
                name: '',
                type: '',
                pictures: [],
                specifications: [
                    {nameKey: '', nameValue: ''}
                ],
                files: [
                    {type: '', fileList: []}
                ],
            };

            //获取所有产品文件类型
            this.getFileTypeAll();
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // alert('submit!');
                    // console.log(this.ruleForm)

                    var fileList = [];
                    this.ruleForm.files.map( item => {
                        fileList.push({type: item.type, fileName: item.fileList[0].name, filePath: item.fileList[0].url})
                    })

                    let picture = this.ruleForm.pictures.map( (flag) => {
                        return flag.url;
                    }).join(',')

                    if(this.ruleForm.id == null){

                        var dataInsert = {
                            name: this.ruleForm.name,
                            pictures: picture,
                            type: this.ruleForm.type,
                            files: fileList,
                            specifications: this.ruleForm.specifications,
                        }

                        //新增
                        console.log("新增")
                        product("/save", "post", {...removeNullUndefined(dataInsert)}, 1).then((res) => {
                            if (res.code == 200){
                                this.$message.success(res.message);
                                this.fetchData();
                            }
                        }).finally(() => {
                            // this.resetForm(formName)
                            this.ruleForm = {
                                name: '',
                                type: '',
                                pictures: [],
                                specifications: [
                                    {nameKey: '', nameValue: ''}
                                ],
                                files: [
                                    {type: '', fileList: []}
                                ],
                            };
                            this.insertVisible = false;
                        })
                    }else {
                        //编辑
                        console.log("编辑")

                        var dataUpdate = {
                            id: this.ruleForm.id,
                            name: this.ruleForm.name,
                            pictures: picture,
                            type: this.ruleForm.type,
                            files: fileList,
                            specifications: this.ruleForm.specifications,
                        }

                        console.log(dataUpdate)

                        product("/update", "post", {...removeNullUndefined(dataUpdate)}, 1).then((res) => {
                            if (res.code == 200){
                                this.$message.success(res.message);
                                this.fetchData();
                            }
                        }).finally(() => {
                            // this.resetForm(formName)
                            this.ruleForm = {
                                id: '',
                                name: '',
                                type: '',
                                pictures: [],
                                specifications: [
                                    {nameKey: '', nameValue: ''}
                                ],
                                files: [
                                    {type: '', fileList: []}
                                ],
                            };
                            this.insertVisible = false;
                        })
                    }

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.dialogImageUrl = '';
            this.$refs.productPictures.clearFiles();
        },
        removeDomain(item) {
            var index = this.ruleForm.specifications.indexOf(item)
            if (index !== -1) {
                this.ruleForm.specifications.splice(index, 1)
            }
        },
        addDomain() {
            this.ruleForm.specifications.push({
                key: '',
                value: '',
            });
        },
        removeFiles(item){
            var index = this.ruleForm.files.indexOf(item)
            if (index !== -1) {
                this.ruleForm.files.splice(index, 1)
            }
        },
        addFiles(){
            this.ruleForm.files.push({
                type: '',
                fileList: []
            })
        },

        handleDelete(row) {
            handleConfirm("删除后不可恢复,并且影响设备上的产品介绍二维码，确定继续？", "warning", "提示")
                .then((res) => {
                    this.doDelete(row);
                })
                .catch((err) => {
                });
        },
        doDelete(row) {
            product(`/${row.id}`, "delete").then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.message);
                    this.fetchData();
                }
            });
        },

        zoomInFile(url){
            this.dialogImageUrl = url.path + url.name;
            this.dialogVisible = true;
        },
        deletePicture(url){

            this.ruleForm.pictures.some((item,index) => {
                if (item.name === url.name){
                    this.ruleForm.pictures.splice(index, 1)
                    return true;
                }
            })
        },
        handleRemove(file, fileList) {
            // console.log(file, fileList);
            if (this.ruleForm.pictures && this.ruleForm.pictures.length > 0) {
                this.ruleForm.pictures.some((item, index) => {
                    if (item.name === file.name) {
                        this.ruleForm.pictures.splice(index, 1)
                        return true;
                    }
                })
            }
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        uploadRequest(file) {
            //自定义上传
            let formData = new FormData();
            formData.append("file", file.file);

            product("/upload", "post", formData, 1)
                .then((res) => {
                    if (res.code == 200) {
                        let datas = res.data;
                        // this.dialogForm.url = datas.fileUrl;
                        this.ruleForm.pictures.push({url: datas.fileUrl, name: datas.fileUrl, path:this.IMGLink})
                    }
                })
        },

        //生成二维码
        handleGenerate(row) {
            product('/QRCode/generate', "get", {code: row.code}, 2).catch((res) => {

                const blob = new Blob([res.data], {type: "image/png"}); //构造一个blob对象来处理数据
                const fileName = row.code + '.png'; // 下载的文件名称 可以自定义
                //对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
                //IE10以上支持blob但是依然不支持download
                if ("download" in document.createElement("a")) {
                    //支持a标签download的浏览器
                    const link = document.createElement("a"); //创建a标签
                    link.download = fileName; //a标签添加属性
                    link.style.display = "none";
                    link.href = URL.createObjectURL(blob);
                    document.body.appendChild(link);
                    link.click(); //执行下载
                    URL.revokeObjectURL(link.href); //释放url
                    document.body.removeChild(link); //释放标签
                } else {
                    //其他浏览器
                    navigator.msSaveBlob(blob, fileName);
                }

            })
        },

        //获取所有产品文件类型
        getFileTypeAll(){
            product("/file/type/all", "post").then( (res) => {
                this.fileTypeOption = res.data;
            })
        },
        querySearchAsync(queryString, cb) {
            // console.log(queryString)
            console.log(cb)

            var restaurants = this.fileTypeOption.map((item) => {
                let param = {value: item.type}
                return param;
            });
            console.log(restaurants)
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;

            console.log(results)
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
                cb(results);
            }, 1000 * Math.random());
        },
        createFilter(queryString) {
            return (state) => {
                return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        handleSelect(item) {
            console.log(item);
        },

        //文件上传
        handleAvatarSuccess(res, file) { },
        uploadFilesRequest(file, index){

            // 自定义上传
            let formData = new FormData();
            formData.append("file", file.file);

            this.uploading = true;
            product("/upload", "post", formData, 1)
                .then((res) => {
                    if (res.code == 200) {
                        let datas = res.data;
                        this.ruleForm.files[index].fileList = [{name: datas.originalFilename, url: datas.fileUrl}]
                    }
                }).finally(() => {
                    this.uploading = false;
                })
        },
    }
}
</script>

<style lang="scss" scoped>
.ipt {
    width: 95%;
}

.searchForm {
    padding-left: 8px;

    .el-form-item {
        margin-bottom: 8px;
    }
}

::v-deep.home-confirm-dialog .el-dialog__body {
    max-height: calc(90vh - 100px);
    overflow: auto;
    border-top: 1px solid #dfdfdf;
    border-bottom: 1px solid #dfdfdf;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}

//::v-deep .el-dialog {
//    position: fixed;
//    height: fit-content;
//    left: 0 !important;
//    right: 0 !important;
//    top: 0 !important;
//    bottom: 0 !important;
//    margin: auto !important;
//}

.el-col {
    border-radius: 4px;
}

.disabled .el-upload--picture-card{
    display: none
}

</style>
